package com.ts.api.http.org.biz;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.digest.MD5;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.ts.api.http.org.entity.apply.OrgApplyRuiYou;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.org.handler.ApiOrgPhoneMd5ConvertHandler;
import com.ts.api.module.api.convert.org.model.RespOrgPhoneMd5Apply;
import com.ts.api.module.api.convert.org.model.RespOrgPhoneMd5DataExchange;

import java.util.Map;

/**
 * 安心分期-瑞友-南京-api
 *  链接：https://www.yuque.com/u33825202/xtwksg/pq9vsht5bw81oysd?singleDoc#
 *  密码： rdac
 *
 * @author gwc
 * @create 2025-08-13 下午2:41
 */
@ApiPlan(productId = "339", type = ApiPlanConvertType.ORG_PHONE_MD5)
public class ApiOrgPhoneMd5RuiYou implements ApiOrgPhoneMd5ConvertHandler {

    private static final String APP_KEY = "cc47e445de364ee49aba06d2cbe2177b";
    private static final String APP_SECRET = "b1a5df49bd0948dd86a8142b5a8ae008";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        // 手机号
        String phone = apiDataExchangeParameter.getPhoneMd5();
        // 签名
         String signstr = "appKey=" + APP_KEY + "&phone=" + phone + APP_SECRET;
        Map<Object, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("appKey", APP_KEY);
            newMap.put("phone", phone);
            newMap.put("isMask", "1");
            newMap.put("sign", MD5.create().digestToHex(signstr, false));
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespOrgPhoneMd5DataExchange respDataExchange(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespOrgPhoneMd5DataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("errCode"), 0)) {
            return RespOrgPhoneMd5DataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getString("data"), "true")) {
            return RespOrgPhoneMd5DataExchange.ofFail();
        }
        return RespOrgPhoneMd5DataExchange.ofSuc();
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {
        // 创建进件实体类
        OrgApplyRuiYou ruiYouData = new OrgApplyRuiYou();
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyParameter);
        // appKey
        ruiYouData.setAppKey(APP_KEY);
        // 是否加密，默认0 不加密；1加密
        ruiYouData.setIsMask("0");
        // 手机号
        ruiYouData.setPhone(apiApplyParameter.getPhone());
        // 客户姓名
        ruiYouData.setName(apiApplyParameter.getUserName());
        // 申请额度/意向金额 如：1000
        ruiYouData.setApplyAmount(String.valueOf(apiFieldConverter.getLoanAmountInt()));
        // 年龄
        ruiYouData.setAge(apiFieldConverter.getAge());
        // 是否有保单 1=有 2=无
        String baodanIs = ChooseEq.create()
                .when(apiApplyParameter.getInsurancePolicy(), "1", "2")
                .when(apiApplyParameter.getInsurancePolicy(), "2", "1")
                .when(apiApplyParameter.getInsurancePolicy(), "3", "1")
                .when(apiApplyParameter.getInsurancePolicy(), "4", "1")
                .end("2");
        ruiYouData.setWarranty(baodanIs);
        // 是否有公积金 1=有 2=无
        String gongjijin = ChooseEq.create()
                .when(apiApplyParameter.getProvidentFund(), "1", "2")
                .when(apiApplyParameter.getProvidentFund(), "2", "1")
                .when(apiApplyParameter.getProvidentFund(), "3", "1")
                .when(apiApplyParameter.getProvidentFund(), "4", "1")
                .end("2");
        ruiYouData.setAccumulation(gongjijin);
        // 有社保, 1=有 2=无
        String shebao = ChooseEq.create()
                .when(apiApplyParameter.getSocialSecurity(), "1", "2")
                .when(apiApplyParameter.getSocialSecurity(), "2", "1")
                .when(apiApplyParameter.getSocialSecurity(), "3", "1")
                .when(apiApplyParameter.getSocialSecurity(), "4", "1")
                .end("2");
        ruiYouData.setSocial(shebao);
        // 是否有房 1=有 2=无
        String house = ChooseEq.create()
                .when(apiApplyParameter.getRealEstateInfo(), "1", "2")
                .when(apiApplyParameter.getRealEstateInfo(), "2", "1")
                .when(apiApplyParameter.getRealEstateInfo(), "3", "1")
                .when(apiApplyParameter.getRealEstateInfo(), "4", "1")
                .when(apiApplyParameter.getRealEstateInfo(), "5", "1")
                .when(apiApplyParameter.getRealEstateInfo(), "6", "1")
                .end("2");
        ruiYouData.setHouse(house);
        // 是否有车 1=有 2=无
        String car = ChooseEq.create()
                .when(apiApplyParameter.getCarInfo(), "1", "2")
                .when(apiApplyParameter.getCarInfo(), "2", "1")
                .when(apiApplyParameter.getCarInfo(), "3", "1")
                .when(apiApplyParameter.getCarInfo(), "4", "1")
                .end("2");
        ruiYouData.setCar(car);
        // 代发 1=有 2=无
        String isbankpay = ChooseEq.create()
                .when(apiApplyParameter.getSalaryPayMethod(), "1", "1")
                .when(apiApplyParameter.getSalaryPayMethod(), "2", "2")
                .when(apiApplyParameter.getSalaryPayMethod(), "3", "2")
                .end("2");
        ruiYouData.setIssuing(isbankpay);
        // 企业纳税 1=有 2=无
        ruiYouData.setPayment("2");
        // 企业开票 1=有 2=无
        ruiYouData.setBilling("2");
        // 参数拼接字符串appKey=asd&phone=13012345678，尾部再添加appSecret，
        // 进行MD5加密：md5(appKey={appKey}&phone={phone}+{appSecret})，
        // 加密后字符串转化为大写。
        // 注：签名中的phone值，随是否加密改变，如果isMask为1，请使用aes加密后的手机号
        // 签名
        String signstr = "appKey=" + APP_KEY + "&phone=" + apiApplyParameter.getPhone() + APP_SECRET;
        ruiYouData.setSign(MD5.create().digestToHex(signstr, false));
        // 备注
        ruiYouData.setRemark(apiApplyParameter.getFormRemark());
        // 学历：0为初中，1为高中，2为大专，3为本科，4为硕士，5为博士
        String eduChoose = ChooseEq.create()
                .when(apiApplyParameter.getEducationAttainment(), "1", "0")
                .when(apiApplyParameter.getEducationAttainment(), "2", "1")
                .when(apiApplyParameter.getEducationAttainment(), "3", "1")
                .when(apiApplyParameter.getEducationAttainment(), "4", "2")
                .when(apiApplyParameter.getEducationAttainment(), "5", "3")
                .when(apiApplyParameter.getEducationAttainment(), "6", "4")
                .end("0");
        ruiYouData.setQualification(eduChoose);
        // 性别：0：未知；1：男；2：女
        String sex = ChooseEq.create()
                .when(apiApplyParameter.getSex(), "0", "1")
                .when(apiApplyParameter.getSex(), "1", "2")
                .when(apiApplyParameter.getSex(), "2", "0")
                .end("0");
        ruiYouData.setGender(sex);
        // 如果是直辖市则 province 和 city 字段相同，例如北京、天津、上海、重庆。
        if(Eq.strOr(apiApplyParameter.getCity(), "北京市", "天津市", "上海市", "重庆市")) {
            ruiYouData.setProvince(apiApplyParameter.getCity().replace("市", ""));
        }else{
            // 省份名称，例如：浙江，安徽；不带“省”这个字
            ruiYouData.setProvince(apiApplyParameter.getProvinceName().replace("省", ""));
        }
        // 市级名称；例如：杭州，宁波；不带“市”这个字。
        ruiYouData.setCity(apiApplyParameter.getCity().replace("市", ""));
        return JsonUtils.toJson(ruiYouData);
    }

    @Override
    public RespOrgPhoneMd5Apply respApply(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespOrgPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("errCode"), 0)) {
            return RespOrgPhoneMd5Apply.ofFail();
        }
        return RespOrgPhoneMd5Apply.ofSuc();
    }
}
